using System.Diagnostics;
using System.Runtime.InteropServices;
using Vin.Extension.Win32.Command.Process;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Win32;
using Vin.Win32.EventArgs;
using Vin.Win32.Hooks;
using Vin.Win32.Input;
using Vin.Win32.Input.Enum;
using Win32;
using Win32.API;
using Win32.Hooks;
using WindowsInput;
using WindowsInput.Native;
using Button = System.Windows.Forms.Button;
using UIA = Interop.UIAutomationClient;
using WorkflowManager = Vin.Extension.Win32.Command.Workflow.WorkflowManager;

namespace Win32ApiTest;

public partial class Form1 : Form
{
    // 定义需要的Win32 API函数
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, string lParam);

    private IntPtr prevIntPtr = IntPtr.Zero;


    InputSimulator simulator = new InputSimulator();
    
    private IProcessContext _processContext = null!;

    public Form1()
    {
        InitializeComponent();
        this.InstallWin32App();
        Init();
    }

    protected override void OnFormClosed(FormClosedEventArgs e)
    {
        Console.WriteLine("OnFormClosed");
        this.UninstallWin32App();
        base.OnFormClosed(e);
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        VinWin32App.HandleWndProc(m);
    }

    // private void TestWinEventProc(IntPtr hwineventhook, uint eventtype, IntPtr hwnd, int idobject, int idchild,
    //     uint dweventthread, uint dwmseventtime)
    // {
    //     if (prevIntPtr != IntPtr.Zero && hwnd == prevIntPtr)
    //     {
    //         Console.WriteLine("TestWinEventProc:" + hwnd + "," + eventtype);
    //     }
    // }


    public void Init()
    {
        _processContext = VinApp.GetRequiredService<IProcessContext>();
        // var proc = new VinUser32.WinEventProc(TestWinEventProc);
        // VinUser32.SetWinEventHook(VinUser32.WIN_EVENT_MIN, VinUser32.WIN_EVENT_MAX, IntPtr.Zero, proc, 0, 0, 0);


        // Process.EnterDebugMode();
        {
            var btn = new Button();
            btn.Text = "FindWindow";
            btn.Click += (sender, e) => { FindWindow(); };
            Controls.Add(btn);
        }

        {
            var btn = new Button();
            btn.Top = 30;
            btn.Text = "流程";
            btn.Click += (sender, e) => { ExeProcess(); };
            Controls.Add(btn);
        }

        

        // 鼠标钩子
        VinMouseHook mouseHook = new VinMouseHook();
        mouseHook.MiddleDown += (sender, e) =>
        {
            prevIntPtr = Win32.User32.WindowFromPoint(e.X, e.Y);
        
            // 设置当前窗口为前台窗口
        
            // Win32Api.ShowWindow(hwnd, Win32Api.SW_SHOWNORMAL);
        
            Win32Api.SetForegroundWindow(this.Handle);
            // Thread.Sleep(1000);
            //
            // Console.WriteLine("MiddleDown:" + hwnd);
            // // 模拟复制 Ctrl+C
            // SendKeys.SendWait("^V");
            // Thread.Sleep(500);
            // // 获取剪切板内容
            // var text = Clipboard.GetText();
            // Console.WriteLine("MiddleDown:" + text);
        
            return 1;
        };
        mouseHook.Start();

        // KeyboardHook keyboardHook = new KeyboardHook();
        // keyboardHook.OnKeyDown += (sender, e) => { Console.WriteLine("KeyDown:" + e.KeyCode + "," + e.KeyValue); };
        // keyboardHook.Start();

        // Win32.Hooks.MouseHook mouseHook = new Win32.Hooks.MouseHook();
        // mouseHook.MiddleDown += (sender, e) =>
        // {
        //     var hwnd = Win32.User32.WindowFromPoint(e.X, e.Y);
        //     Console.WriteLine("MiddleDown:" + hwnd);
        //     // 模拟复制 Ctrl+C
        //     SendKeys.SendWait("^C");
        //     Thread.Sleep(500);
        //     // 获取剪切板内容
        //     var text = Clipboard.GetText();
        //     Console.WriteLine("MiddleDown:" + text);
        //     
        //     // 拦截事件
        //     
        //     
        //     // var topHwnd = Win32.User32.WindowFromPoint(e.X, e.Y);
        //     // var topElement = automation.ElementFromHandle(topHwnd);
        //     // var edit = topElement.FindFirst(UIA.TreeScope.TreeScope_Descendants,
        //     //     automation.CreatePropertyCondition(UIA.UIA_PropertyIds.UIA_NamePropertyId, "文件传输助手"));
        //     // if (edit != null)
        //     // {
        //     //     var pattern =
        //     //         (UIA.IUIAutomationTextPattern?)edit.GetCurrentPattern(UIA.UIA_PatternIds.UIA_TextPatternId);
        //     //     
        //     //     Console.WriteLine(pattern == null);
        //     //
        //     //     // pattern?.SetValue((string.IsNullOrEmpty(pattern.CurrentValue) ? "" : (pattern.CurrentValue + "-")) +
        //     //     //                   "Hello World");
        //     // }
        //     // var rect = topElement.CurrentBoundingRectangle;
        //     // Console.WriteLine("MiddleDown:" + topHwnd + ":" + rect.left + ":" + rect.top + ":" + rect.right + ":" + rect.bottom);
        //     // var size = new Size(rect.right - rect.left, rect.bottom - rect.top);
        //     // Console.WriteLine("MiddleDown:" + size.Width + ":" + size.Height);
        //     // var children = topElement.FindAll(UIA.TreeScope.TreeScope_Descendants,
        //     //     automation.create)
        //     // var children = topElement.FindAll(UIA.TreeScope.TreeScope_Descendants,automation.crea)
        //     // var count = children.Length;
        //     // Console.WriteLine("MiddleDown:" + count);
        //
        //
        //     // // 坐标转换成窗口内坐标
        //     // var point = new POINT(e.X, e.Y);
        //     // Win32.User32.ScreenToClient(topHwnd, out point);
        //     // Console.WriteLine("MiddleDown:" + e.X + ":" + e.Y + ":" + point.X + ":" + point.Y);
        //     // var hWnd = Win32.User32.ChildWindowFromPointEx(topHwnd, point, Win32Api.CWP_SKIPINVISIBL | 4);
        //     // var childElement = automation.ElementFromHandle(hWnd);
        //     // Console.WriteLine("MiddleDown:" + topHwnd + ":" + hWnd);
        //     // Console.WriteLine("MiddleDown:" + topElement.CurrentClassName + ":" + childElement.CurrentClassName);
        //     // var element = automation.ElementFromHandle(hWnd);
        //
        //     // var title = element.CurrentClassName;
        //     // Console.WriteLine("MiddleDown:" + hWnd + ":" + title);
        //
        //     // Console.WriteLine("MiddleDown"+sender.GetType());
        //     // MessageBox.Show("MiddleDown");
        // };
        // mouseHook.Start();
    }

    public void FindWechat()
    {
        var process = Process.GetProcessesByName("WxWork").FirstOrDefault();
        // var mainWindowHandle = process.MainWindowHandle;
        var app = new FlaUI.Core.Application(process);
        using var automation = new FlaUI.UIA3.UIA3Automation();
        var mainWindow = app.GetMainWindow(automation);
        var elements = mainWindow.FindAll(FlaUI.Core.Definitions.TreeScope.Descendants,
            FlaUI.Core.Conditions.TrueCondition.Default);
        var addressBook = mainWindow.FindFirstDescendant(cf => cf.ByName("通讯录"));
        addressBook.Click();

        // var list = mainWindow.FindAllDescendants(m => m.ByName("文件传输助手"));
        // var edit = mainWindow.FindAllDescendants(m => m.ByName("文件传输助手")).LastOrDefault().AsTextBox();
        // var i = 0;
        // if (edit != null)
        // {
        //     edit.Text = "Hello World";
        // }

        // var edit = AutomationElementExtensions.AsTextBox(mainWindow.FindFirstDescendant(c => c.ByName("文件传输助手")));
        // edit.Text = "Hello World";


        // var wechat = Win32Api.FindWindow(null, "微信"); //Win32Api.FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "微信");
        // var customAutomation = new UIA.CUIAutomation8();
        // var customElement = customAutomation.ElementFromHandle(mainWindowHandle);
        // var editList = customElement.FindAll(UIA.TreeScope.TreeScope_Descendants,customAutomation.CreatePropertyConditionEx(
        //     UIA.UIA_PropertyIds.UIA_NamePropertyId, "文件传输助手", UIA.PropertyConditionFlags.PropertyConditionFlags_None));
        // var count = editList.Length;
        // var topElement = automation.ElementFromHandle(wechat);
        // var editList = topElement.FindAll(UIA.TreeScope.TreeScope_Descendants,
        //     automation.CreatePropertyConditionEx(UIA.UIA_PropertyIds.UIA_NamePropertyId, "问题答疑群",
        //         UIA.PropertyConditionFlags.PropertyConditionFlags_None));
        // var count = editList.Length;
        // var edit = editList;
        // if (edit != null)
        // {
        //     var pattern =
        //         (UIA.IUIAutomationTextPattern?)edit.GetCurrentPattern(UIA.UIA_PatternIds.UIA_TextPatternId);
        //         
        //     Console.WriteLine(pattern == null);
        //
        //     // pattern?.SetValue((string.IsNullOrEmpty(pattern.CurrentValue) ? "" : (pattern.CurrentValue + "-")) +
        //     //                   "Hello World");
        // }
    }

    public async Task ExeProcess()
    {
        // await WorkflowManager.Start("test2.json",new ProcessData()
        // {
        //     PrevFocusWindowHandle = prevIntPtr,
        //     WindowHandle = this.Handle
        // });
        // await WorkflowManager.ReveresStart("guid.json",new ProcessData()
        // {
        //     PrevFocusWindowHandle = prevIntPtr,
        //     WindowHandle = this.Handle
        // });
        
        // await WorkflowTest.WorkflowManager.StartWorkflow("full_workflow.json",new WorkflowTest.ProcessData()
        // {
        //     PrevFocusWindowHandle = prevIntPtr,
        //     WindowHandle = this.Handle
        // });
        
        _processContext.PrevFocusWindowHandle = prevIntPtr;
        await WorkflowManager.StartWorkflow("workflow.json");


        // // 执行一个复制的流程
        // await VinApp.CreateScopeAsync(async (provider) =>
        // {
        //     var commandParams = VinApp.GetRequiredServiceByHttpContext<CommandData>();
        //     commandParams.PrevFocusWindowHandle = prevIntPtr;
        //     commandParams.WindowHandle = prevIntPtr;
        //
        //     var clipboardCommand = VinApp.GetRequiredServiceByHttpContext<SelectedTextCommand>();
        //     await clipboardCommand.Execute(() => { return Task.CompletedTask; });
        // });

        // // 执行一个复制的流程
        // await VinApp.CreateScopeAsync(async (provider) =>
        // {
        //     var commandParams = VinApp.GetRequiredServiceByHttpContext<CommandData>();
        //     commandParams.PrevFocusWindowHandle = prevIntPtr;
        //     commandParams.WindowHandle = prevIntPtr;
        //
        //     var clipboardCommand = VinApp.GetRequiredServiceByHttpContext<SendTextCommand>();
        //     await clipboardCommand.Execute(() => { return Task.CompletedTask; });
        // });
    }

    public void FindWindow()
    {
        // var wechat2 = Win32Api.FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "微信");
        // // var wechat = Win32Api.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Notepad", null);
        // var wechat = Win32Api.FindWindow("WeChatMainWndForPC", null);
        // if (wechat == IntPtr.Zero)
        // {
        //     MessageBox.Show("未找到Notepad窗口");
        //     return;
        // }
        //
        // Win32Api.ShowWindow(wechat, Win32Api.SW_SHOWNORMAL);
        //
        // Win32Api.SetForegroundWindow(wechat);
        // Thread.Sleep(1000);

        #region 模拟获取复制的文本

        // if (prevIntPtr != IntPtr.Zero)
        // {
        //     // Win32Api.ShowWindow(wechat, Win32Api.SW_SHOW);
        //
        //     if (Win32Api.SetForegroundWindow(prevIntPtr))
        //     {
        //         void ClipboardUpdate(object? sender, VinEventArgs e)
        //         {
        //             // 获取剪切板内容
        //             var text = Clipboard.GetText();
        //             Console.WriteLine("GetText:" + text);
        //         }
        //
        //         VinEventManager.Register<ClipboardUpdateEventArg>(ClipboardUpdate);
        //         VinKeyboardSimulator.Current.KeyPress(VinVirtualKeyCode.CONTROL, VinVirtualKeyCode.VK_C);
        //     }
        // }

        #endregion

        #region 模拟输入

        // if (prevIntPtr != IntPtr.Zero)
        // {
        //     // Win32Api.ShowWindow(wechat, Win32Api.SW_SHOW);
        //
        //     Console.WriteLine("SetForegroundWindow:" + prevIntPtr + "," +
        //                       Win32.User32.GetForegroundWindow());
        //     
        //     if (Win32Api.SetForegroundWindow(prevIntPtr))
        //     {
        //         // Thread.Sleep(250);
        //         // var str = "我是一个测试文本，Hello World，你好世界，@#￥%#￥%￥#￥/::+";
        //         // VinKeyboardSimulator.Current.SendText(str);
        //     }
        // }


        // var str = "我是一个测试文本，Hello World，你好世界，@#￥%#￥%￥#￥/::+";
        //
        // foreach (var s in str)
        // {
        //     var keyboardInput = new Win32.KEYBDINPUT()
        //     {
        //         wVk = 0,
        //         dwFlags = Win32.KeyEventFlags.KEYEVENTF_UNICODE,
        //         dwExtraInfo = IntPtr.Zero,
        //         wScan = s,
        //         time = 0
        //     };
        //     var keyInput = Win32.INPUT.KeyboardInput(keyboardInput);
        //     Win32.User32.SendInput(1, new[] { keyInput }, Win32.INPUT.Size);
        // }

        #endregion

        // // 查询classNmae为	RichEditD2DPT 的子窗口
        // var element = automation.ElementFromHandle(wechat);
        // var child = element.FindFirst(UIA.TreeScope.TreeScope_Descendants,
        //     automation.CreatePropertyCondition(UIA.UIA_PropertyIds.UIA_NamePropertyId, "文本编辑器"));
        //
        // // 修改值
        // if (child != null)
        // {
        //     var pattern = (UIA.IUIAutomationValuePattern)child.GetCurrentPattern(UIA.UIA_PatternIds.UIA_ValuePatternId);
        //     pattern.SetValue((string.IsNullOrEmpty(pattern.CurrentValue) ? "" : (pattern.CurrentValue + "-")) +
        //                      "Hello World");
        //     // 移动光标到最后
        //     var textRange =
        //         (UIA.IUIAutomationTextPattern)child.GetCurrentPattern(UIA.UIA_PatternIds.UIA_TextPatternId);
        //     var documentRange = textRange.DocumentRange;
        //     documentRange.Move(UIA.TextUnit.TextUnit_Character, -1);
        //     // documentRange.Select();
        // }

        // // 设置剪切板
        // Clipboard.SetText("Hello World");
        //
        // // Win32Api.ShowWindow(wechat, Win32Api.SW_SHOW);
        // //
        // // Win32Api.SetForegroundWindow(wechat);
        //
        // // 使用快捷键Ctrl+V粘贴剪切板内容
        // SendKeys.SendWait("^V");

        // Clipboard.Clear();
    }
}